import _ from 'lodash';
import { toast } from '@/components/basicComp/Toast';
import { parse } from 'partial-json';
import { svgHtml } from '@/utils/utils';

let str = '';

function setStr(newValue) {
  str = newValue;
}

function getStr() {
 return str
}

function chatMsgWs(data, This) {
  var config = { data, This };
  var obj = data.data;
  const { selectedChat } = This.props;

  console.log(data.sub_type, data);

  if (data.sub_type == 'ERROR') {
    ERROR(config);
    return 
  }

  // 没会话 不处理
  if (!selectedChat) return;

  var wsId = window.ws.config.uuid;

  // 不是当前网页的消息 不处理
  if (wsId != data.client_id) {
    return;
  }

  // 不是当前回话不处理
  if (obj.conversation_id != selectedChat) {
    return;
  }

  // 
  if(data.sub_type != 'AGENT_CALL'){
    // 没说过话不处理
    if (!This.dialog_segment_id) {
      return;
    }
  }
  

  // 用户确认
  if (data.sub_type == 'CALL_USER') CALL_USER(config);

  // 正常ai返回消息
  if (data.type == 'ASSISTANT_MESSAGE') ASSISTANT_MESSAGE(config);

  // 工具调用 开始
  if (data.sub_type == 'TOOL_CALL') TOOL_CALL(config);

  // 工具调用 结束
  if (data.sub_type == 'TOOL_CALL_RESULT') TOOL_CALL_RESULT(config);

  // AGENT 开始
  if (data.sub_type == 'AGENT_CALL') AGENT_CALL(config);

}

var ASSISTANT_MESSAGE = (config) => {
  const { data, This } = config;
  var obj = data.data;
  const {
    value: { changeState },
  } = This.props;

  var store = window.getStore();
  var { chat } = store.getState();

  // ppt
  if (data.payload.json_type == 'ppt') {
    ppt(config);
    return;
  }

  // artifacts
  if (data.payload.json_type == 'artifacts') {
    artifacts(config);
    return;
  }

  // svger
  if (data.payload.json_type == 'svger') {
    svger(config);
    return;
  }

  if(This.dialog_segment_id != obj.dialog_segment_id){
    // 需要创建一条 新数据
    This.dialog_segment_id = obj.dialog_segment_id


    // 添加用户消息
    var messages = [...chat.messages];
    // 机器人空数据
    messages.push({
      role: 'assistant',
      content: [],
      object: null,
      initData: true,
    });
    changeState({ messages: messages });
  }


  // 正常情况
  if (data.group?.status == 'ENDED') {
    clearTimeout(This.heartbeatTimer);
    console.log('终止了');
    This.chatEnd();
    return;
  }

  This.chatTimeNext();

  // 处理消息
  if (obj.content) {
    str += obj.content;

    This.setMessage({
      role: 'ai',
      content: [
        {
          type: 'text',
          text: str,
          itemData: obj,
        },
      ],
      initData: false,
    });

    changeState({ chatLoading: true });
  }
};

var TOOL_CALL = (config) => {
  const { data, This } = config;
  var obj = data.data;

  const {
    value: { changeState, scrollToBottom2 },
  } = This.props;
  // 插入一条

  var store = window.getStore();
  var { chat } = store.getState();

  setStr('');

  // 添加用户消息
  var messages = [...chat.messages];

  // 机器人空数据
  messages.push({
    ...obj,
    role: 'ai',
    content: [],
    object: null,
    tool_calls: obj.tool_calls,
  });

  var toolObj = { ...chat.toolObj };

  obj.tool_calls.forEach((item, i) => {
    toolObj[item.id] = item.id;
  });

  changeState({
    chatLoading: true,
    messages: messages,
    toolObj: toolObj,
  });

  This.scrollTime = setTimeout(() => {
    clearTimeout(This.scrollTime);
    scrollToBottom2();
  }, 20);

  console.log('TOOL_CALL');
  console.log(data);
};

var TOOL_CALL_RESULT = (config) => {
  const { data, This } = config;
  var obj = data.data;
  const {
    value: { changeState, scrollToBottom2 },
  } = This.props;

  setTimeout(() => {
    var store = window.getStore();
    var { chat } = store.getState();

    var toolObj = { ...chat.toolObj };
    obj.tool_calls.forEach((item, i) => {
      var id = item.tool_call_id;
      delete toolObj[id];
    });

    changeState({
      chatLoading: false,
      toolObj: toolObj,
    });

    This.scrollTime = setTimeout(() => {
      clearTimeout(This.scrollTime);
      scrollToBottom2();
    }, 20);
  }, 1500);
};

var ERROR = (config) => {
  const { data, This } = config;
  var obj = data.data;
  const {
    value: { changeState, scrollToBottom2 },
  } = This.props;
  toast.error(obj.message,5000);
  This.chatClose()
};

var CALL_USER = (config) => {
  // 这里需要去看确认类型 
  const { data, This } = config;
  if(data.payload.confirm_type == 'ppt'){
    return 
  }
  This.user_confirm = data
  This.setState({ showConfirmDialog: true });
};

var AGENT_CALL = (config) => {
  const { data, This } = config;
  const {
    value: { changeState, },
  } = This.props;
  // 插入一条

  var store = window.getStore();
  var { chat } = store.getState();

  var agentObj = { ...chat.agentObj };

  var id = data.dialog_segment_id
  agentObj[id] = id

  changeState({
    chatLoading: true,
    agentObj: agentObj,
  });

  console.log('AGENT_CALL');
  
};

var ppt = (config) => {
  const { data, This } = config;
  var obj = data.data;
  const {
    value: { changeState },
  } = This.props;

  var store = window.getStore();
  var { chat } = store.getState();

  if (This.dialog_segment_id != obj.dialog_segment_id) {
    // 需要创建一条 新数据
    This.dialog_segment_id = obj.dialog_segment_id;

    // 添加用户消息
    var messages = [...chat.messages];
    // 机器人空数据
    messages.push({
      role: 'assistant',
      content: [],
      object: null,
      initData: true,
    });
    changeState({ messages: messages });
  }

  // 正常情况
  if (data.group?.status == 'ENDED') {
    clearTimeout(This.heartbeatTimer);
    console.log('终止了');
    This.chatEnd();
    var { chat } = store.getState();
    var newList = JSON.parse(JSON.stringify(chat.messages))
    
    newList.forEach((item)=>{
      if(item.ppt?.type =='2'){
        item.ppt.type = '1'
        item.ppt.isEdn = true
      }
    })
    
    changeState({ messages: newList });
    return;
  }

  This.chatTimeNext();

  // 处理消息
  if (obj.content) {
    str += obj.content;
    var jsonObj = null
    try { 
      jsonObj = parse(str);
    } catch (e) {}
    console.log(jsonObj)

    if (jsonObj) {

      // 处理ppt插入逻辑
      if (!jsonObj.html_code) {
        This.setMessage({
          role: 'ai',
          content: [
            {
              type: 'text',
              text: jsonObj.response,
            },
          ],
          initData: false,
        });

        changeState({ chatLoading: true });
      }

      // 处理ppt插入逻辑
      if (jsonObj.html_code) {
        var ppt = {
          ...jsonObj,
          id:data.id,
          code: jsonObj.html_code,
          thinking: '',
          type: '2',
          width:1280,
          height:720,
          isEdn:false,
        }

        This.setMessage({
          ...data,
          content: [],
          ppt: ppt,
        });

        console.log('----------')
        console.log({
          ...data,
          dialog_segment_id:data.data.dialog_segment_id,
          content: [],
          ppt: ppt,
        })
        console.log('----------')

        changeState({
          openPreview: true,
          previewType: 'ppt',
        });


      }
    }


    changeState({ chatLoading: true });
  }

  console.log('ppt');
};

var artifacts = (config) => {

  const { data, This } = config;
  var obj = data.data;
  const {
    value: { changeState },
  } = This.props;


  // 正常情况
  if (data.group?.status == 'ENDED') {
    var content = obj.content || '';
    if (content) str += content;
    clearTimeout(This.heartbeatTimer);
    console.log('终止了');
    This.chatEnd();
    return;
  }

 // 处理生成代码
 if (true) {
  var content = obj.content || '';
  // Remove code block markers with any language identifier
  content = content.replace(/```[\w-]*\n?/g, '');
  str += content;
  str = str.replace(/^[\w-]*\n?/, '');

  if (str.length > 4) {
    var itemObj = parse(str);
    changeState({
      fragment: itemObj,
      openPreview: true,
      currentTab: 'code',
      previewType: 'e2b',
    });

    setTimeout(() => {
      This.closeMenu();
    }, 100);

    const content2 = [
      { type: 'text', text: itemObj.commentary || '' },
      { type: 'code', text: itemObj.code || '' },
    ];

    This.setMessage({
      content: content2,
      object: itemObj,
      initData: false,
    });
  }
}

  

};

var svger = (config) => {
  const { data, This } = config;
  var obj = data.data;
  const {
    value: { changeState },
  } = This.props;

  var store = window.getStore();
  var { chat } = store.getState();

  if (This.dialog_segment_id != obj.dialog_segment_id) {
    // 需要创建一条 新数据
    This.dialog_segment_id = obj.dialog_segment_id;

    // 添加用户消息
    var messages = [...chat.messages];
    // 机器人空数据
    messages.push({
      role: 'assistant',
      content: [],
      object: null,
      initData: true,
    });
    changeState({ messages: messages });
  }

  // 正常情况
  if (data.group?.status == 'ENDED') {
    clearTimeout(This.heartbeatTimer);
    console.log('终止了');
    This.chatEnd();
    changeState({currentTab: 'fragment'});
    return;
  }

  This.chatTimeNext();

  
  // 处理消息
  if (obj.content) {
    str += obj.content;
    console.log(str)

    changeState({
      previewType: 'iframe',
      openPreview: true,
      fragment: {
        code: svgHtml(str),
        file_path: 'index.html',
      },
    });

    setTimeout(() => {
      This.closeMenu();
    }, 100);

    This.setMessage({
      content: [],
      svger: {
        svg:svgHtml(str)
      },
      initData: false,
    });

  }

  console.log('svger');
};

export { chatMsgWs, setStr, str,getStr };
export default { chatMsgWs, setStr, str,getStr };
